package cn.qy.java.base.ch21;

/**
 * wait 案例一：一个线程也能使用 wait。
 *
 * @author acc8226
 */
public class Ch21_02_ThreadWaitDemo extends Thread {
	
	boolean isFired = false;
	
	@Override
	public void run() {
		try {
			synchronized (this) {
				while (!isFired) {
					System.out.println("thread before wait");
					// 调用 wait，线程会释放锁
					wait();
					System.out.println("thread end wait");
				}
			}
			System.out.println("fired");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void fire() {
		// 用于打破 wait 中使用的循环条件
		isFired = true;
		notify();
	}
	
	public static void main(String[] args) throws InterruptedException {
		Ch21_02_ThreadWaitDemo thread = new Ch21_02_ThreadWaitDemo();
		thread.start();
		Thread.sleep(2000);
		thread.fire();
	}

}
